/**
  * <br>JAVACC DEMO 1.0<br>
  * @copy right ius company All rights reserved.<br>
  * <br>
  * @Package com.apache.action
*/
package com.apache.action;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.apache.api.entity.BaseEntity;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import org.springframework.web.servlet.ModelAndView;

/**
  * description: springmvc的基类，公共方法
  * @author Hou DaYu 创建时间：上午10:12:47
  */
public abstract class ActionSupport<T extends BaseEntity> {

	protected Logger logger = Logger.getLogger(this.getClass());

	protected abstract BaseManager<T> getBaseManager();

	protected abstract String getPrefix();

	protected abstract Object data(HttpServletRequest request,
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows);

	protected final String ADD = getPrefix() + "save";
	protected final String EDIT = getPrefix() + "save";
	protected final String VIEW = getPrefix() + "view";
	protected final String LIST = getPrefix() + "list";

	/**
	 * 功能说明：通用跳转到列表查询页面
	 */
	@RequestMapping("list.action")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView(LIST);
	}

	/**
	 * 功能说明：通用跳转到编辑页面
	 */
	@Token(save = true)
	@RequestMapping(value = "/edit.action")
	public ModelAndView edit(HttpServletRequest request, String id) {
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		ModelAndView view = new ModelAndView(EDIT);
		view.addObject("item", getBaseManager().getInfoById(vo));
		view.addObject("isAdd", "false");
		return view;
	}

	@RequestMapping(value = "/view.action")
	public ModelAndView view(Model model, String id) {
		ModelAndView view = new ModelAndView(VIEW);
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		Object obj = getBaseManager().getInfoById(vo);
		view.addObject("item", obj);
		return view;
	}

	/**
	 * 功能说明：通用保存页面
	 */
	@Token(remove = true)
	@RequestMapping(value = "/save.action", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg save(HttpServletRequest request, HttpServletResponse response, @ModelAttribute T item) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		String isAdd = getDefaultStr(request.getParameter("isAdd"), "true");
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setObj(item);
		String id = "";
		boolean mark = false;
		if ("false".equals(isAdd) && item != null) {
			mark = getBaseManager().editInfo(vo);
		} else {
			id = getBaseManager().saveInfo(vo);
		}
		if (("false".equals(isAdd) && !mark) || ("true".equals(isAdd) && isNull(id))) {
			rmsg.setFlag("F");
			rmsg.setMsg("操作失败！");
		}
		return rmsg;
	}

	/**
	 * 功能说明：通用删除功能
	 * @updated
	 * @param id   删除的id
	 */
	@RequestMapping(value = "/del.action")
	@ResponseBody
	public ResultMsg delete(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg("T", "删除成功！");
		ParamsVo<T> vo = new ParamsVo<T>();
		if (isNotNull(id)) {
			vo.setInfoId(id);
			boolean mark = getBaseManager().deleteInfo(vo);
			if (!mark) {
				rmsg.setFlag("F");
				rmsg.setMsg("删除失败！");
			}
		} else {
			rmsg.setFlag("H");
			rmsg.setMsg("请不要恶意操作！");
		}
		return rmsg;
	}

	//	@InitBinder
	//	protected void initBinder(WebDataBinder binder) {
	//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	//		dateFormat.setLenient(false);
	//		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	//	}

	protected ResultMsg getResultMsg(HttpServletRequest request, String msg) {
		request.getSession().setAttribute("formToken", request.getAttribute("formToken"));
		ResultMsg rmsg = new ResultMsg("F", msg);
		return rmsg;
	}

	/**
	 * description:  获取访问IP
	 * @param request 当前请求
	 * @return   
	 * @author Hou Dayu  
	 * @update 2014-8-7
	 */
	protected String getUserIp(HttpServletRequest request) {
		String ip = "";
		try {
			ip = request.getHeader("x-forwarded-for");
			if (isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (isNotNull(ip) && ip.length() > 32) {
				ip = ip.substring(0, 32);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return ip;
	}

	/**
	 *判断一个字符串是否为空
	 * 
	 * @param  str 传入的字符串
	 * @return     如果str为空返回true，不为空返回false 
	 */
	protected boolean isNull(String str) {
		if (str == null) {
			return true;
		}
		str = str.trim();
		if ((str.equals("null")) || (str.equals(""))) {
			return true;
		}
		return false;
	}

	/**
	 *判断字符串不能为空
	 * 
	 * @param  str 传入的字符串
	 * @return     如果str不为空返回true，为空返回false   
	 */
	protected boolean isNotNull(String str) {
		return !isNull(str);
	}

	/**
	  * description: 判断字符串是否为空，如果为空取给定的默认值
	  * @param text       传入的字符串
	  * @param defaultStr 给定的默认值
	 */
	protected String getDefaultStr(String text, String defaultStr) {
		if (isNull(text))
			return defaultStr;
		return text;
	}

	protected String getGenType() {
		Type genType = getClass().getGenericSuperclass();
		Type[] ddd = ((ParameterizedType) genType).getActualTypeArguments();
		String className = ddd[0].toString().replaceAll("class", "");
		return className.toString();
	}
}
